%%%-------------------------------------------------------------------
%%%    BASIC INFORMATION
%%%-------------------------------------------------------------------
%%% @copyright 2006 Erlang Training & Consulting Ltd
%%% @author  Martin Carlson <martin@erlang-consulting.com>
%%% @version 0.0.1
%%% @doc
%%% @end
%%%-------------------------------------------------------------------
-module(sql_lib).

%% API
-export([to_sql_date/1,
	 to_sql_time/1,
	 escape/1]).

%%====================================================================
%% API
%%====================================================================
to_sql_date({YY,M,D}) ->
	MM = zerofill(M),
	DD = zerofill(D),
	lists:concat([YY, "-", MM, "-", DD]);
to_sql_date({{YY,M,D}, {H, N, S}}) ->
	MM = zerofill(M),
	DD = zerofill(D),
	HH = zerofill(H),
	NN = zerofill(N),
	SS = zerofill(S),	
	lists:concat([YY, "-", MM, "-", DD, " ", HH, ":", NN, ":", SS]).

to_sql_time({H,M,S}) ->
	HH = zerofill(H),
	MM = zerofill(M),
	SS = zerofill(S),	
	lists:concat([HH, ":", MM, ":", SS]).

escape(Str) ->
	sqlescape(Str, []).

%%====================================================================
%% Internal functions
%%====================================================================
zerofill(N) when N > 9 ->
    integer_to_list(N);
zerofill(N) ->
    "0" ++ integer_to_list(N).

sqlescape([], Acc) ->
    lists:reverse(Acc);
sqlescape([$-, $-|T], Acc) ->
    sqlescape(T, Acc);
sqlescape([$\\, $'|T], Acc) ->
    sqlescape(T, [$', $\\|Acc]);
sqlescape([$'|T], Acc) ->
    sqlescape(T, [$', $\\|Acc]);
sqlescape([H|T], Acc) ->
    sqlescape(T, [H|Acc]).
